from fastapi import HTTPException
from sqlalchemy import or_

from app.core.custom_exception import NotFoundException
from app.crud.base_crud import BaseCRUD
from app.models import User
from app.models.login_log import LoginLog
from app.schemas.login_log_schema import LoginLogCreate


class LoginLogCRUD(BaseCRUD[LoginLog, LoginLogCreate, None]):
    async def create(self, obj: LoginLogCreate) -> LoginLog:
        """
        创建新数据
        :param obj: 创建数据的schema
        :return: 创建的数据对象
        :raises HTTPException: 409 如果数据已存在
        """
        user = (await self.context.set(User)
                .where(
                or_(User.username == obj.account,User.phone_number == obj.account,User.email == obj.account),
                User.is_enabled == True)
                .scalar_one_or_none())
        if user is None:
            raise NotFoundException(message="当前用户不存在")
        obj.user_id = user.id
        db_obj = self.model.model_validate(obj)
        return await self.context.add(entity=db_obj)
